#!/usr/bin/env python3
"""
超简单的YAML冲突检测工具 - 5分钟实现版本
遵循"简洁胜于复杂"的理念，只做最重要的检测
"""

import os
import yaml
from pathlib import Path
from collections import defaultdict

def simple_conflict_check(rules_dir="rules"):
    """简单的冲突检测 - 只检测最关键的问题"""
    
    print("🔍 开始简单冲突检测...")
    
    # 收集所有概念
    concepts = defaultdict(list)
    files_info = {}
    
    # 扫描YAML文件
    for yaml_file in Path(rules_dir).rglob("*.yaml"):
        try:
            with open(yaml_file, 'r', encoding='utf-8') as f:
                content = yaml.safe_load(f)
                if content:
                    # 提取文件信息
                    metadata = content.get('rule_metadata', {})
                    category = metadata.get('category', 'unknown')
                    name = metadata.get('name', yaml_file.stem)
                    
                    files_info[str(yaml_file)] = {
                        'name': name,
                        'category': category,
                        'concepts': []
                    }
                    
                    # 查找关键概念（简单字符串匹配）
                    content_str = str(content).lower()
                    key_concepts = [
                        'security', 'authentication', 'authorization',
                        'configuration', 'database', 'api',
                        'monitoring', 'logging', 'performance',
                        'testing', 'deployment', 'cicd'
                    ]
                    
                    for concept in key_concepts:
                        if concept in content_str:
                            concepts[concept].append(str(yaml_file))
                            files_info[str(yaml_file)]['concepts'].append(concept)
                            
        except Exception as e:
            print(f"⚠️  跳过文件 {yaml_file}: {e}")
    
    # 检测冲突
    print("\n📊 冲突检测结果:")
    
    conflicts_found = False
    for concept, files in concepts.items():
        if len(files) > 1:
            print(f"🚨 概念 '{concept}' 出现在多个文件中:")
            for file in files:
                info = files_info.get(file, {})
                print(f"   - {file} (category: {info.get('category', 'unknown')})")
            conflicts_found = True
            print()
    
    if not conflicts_found:
        print("✅ 没有发现明显冲突！")
    
    # 统计信息
    print(f"\n📈 统计信息:")
    print(f"   - 扫描文件: {len(files_info)} 个")
    print(f"   - 发现概念: {len(concepts)} 个")
    print(f"   - 潜在冲突: {sum(1 for files in concepts.values() if len(files) > 1)} 个")
    
    return not conflicts_found

def quick_fix_suggestions():
    """提供快速修复建议"""
    
    print("\n💡 快速修复建议:")
    print("1. 如果同一概念出现在多个文件：")
    print("   - 选择最合适的文件保留")
    print("   - 其他文件使用 'extends' 继承")
    print()
    print("2. 如果不确定如何选择：")
    print("   - core > system > evolution > project (按优先级)")
    print("   - 专用文件 > 通用文件")
    print()
    print("3. 预防未来冲突：")
    print("   - 新建YAML前先搜索: grep -r '概念' rules/")
    print("   - 遵循单一职责原则")
    print("   - 明确声明继承关系")

def main():
    """主函数 - 简洁明了"""
    
    print("🚀 intelligent_rules_v2 - 超简单YAML冲突检测")
    print("=" * 50)
    
    # 检测冲突
    is_clean = simple_conflict_check()
    
    # 提供建议
    if not is_clean:
        quick_fix_suggestions()
    
    print("\n✨ 检测完成！记住：简洁胜于复杂")
    
    return is_clean

if __name__ == "__main__":
    main() 